package util.payUtil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.example.administrator.text.HomeActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import data.SharedPreferencesUtils;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import view.diaLogView.UploadDialog;

/**
 * Created by liuxiaobin on 2016/10/23
 *支付的工具类
 * Arrays.sort(strs); stra是数组 Arrays是对字符串 按字母来排序
 */

public class PayUtil {
    private static PayUtil mPayUtil;
    public  Activity mActivity;
    /** 支付宝支付业务：入参app_id */
    public static final String APPID = "";
    /** 商户私钥，pkcs8格式 */
    public static final String RSA_PRIVATE = "";
    private Map<String,Object> mMap;
    private static final int SDK_PAY_FLAG = 1;
    private UploadDialog mUploadDialog;
    private static final int SDK_AUTH_FLAG = 2;
    private Logger mLogger = Logger.getLogger(PayUtil.class);
    public static String PAY_ORSER = "order";                          //支付的订单
    public static String PAY_COMMODITY = "commodity";                 //商品

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    String string = (String)SharedPreferencesUtils.getParam(mActivity,PAY_ORSER,"");
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        getQueryPay(string);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        getQueryPay(string);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(mActivity,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(mActivity,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    public static synchronized PayUtil NewPayUtil(){
        if(mPayUtil == null){
            return mPayUtil = new PayUtil();
        }else {
            return mPayUtil;
        }
    }

    /**
     * sign 签名
     * timeStamp 时间戳
     * nonceStr 随机字符串
     * prepayId 微信返回的支付交易会话ID
     * @param context 用于微信支付   wx7e6aad647ba8afa1
     */
    private void getWeChatPay(Context context,String prepayId,String packageValue,String nonceStr,String timeStamp,String sign,String partnerid){
        //String appid = "wxd39c334682ba719c";                   //微信开发平台注册应用时 生成的appid  牛郎app
        String appid = "wx7e6aad647ba8afa1";                   //微信开发平台注册应用时 生成的appid    NewFi
        IWXAPI api;
        api = WXAPIFactory.createWXAPI(context,appid,false);  // 通过WXAPIFactory工厂，获取IWXAPI的实例 ""为APPID
        api.registerApp(appid);                              //将该app注册到微信 "" 为APPID
        PayReq request = new PayReq();
        request.appId = appid;
        request.partnerId = partnerid;
        request.prepayId= prepayId;
        request.packageValue = packageValue;
        request.nonceStr= nonceStr;
        request.timeStamp= timeStamp;
        request.sign= sign;
        boolean sendReq = api.sendReq(request); //调起微信支付SDK
        if(!sendReq){Toast.makeText(context,"调起微信支付SDK失败",Toast.LENGTH_SHORT).show();}
        mLogger.info("getFEQWeChatPay()---微信>调起微信支付SDK状态()--String"+sendReq);
    }

    /**
     * 支付宝的调用
     */
    public void getAlipay( final String orderInfo){

        Runnable payRunnable = new Runnable() {
            @Override public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝  先调用自己后台
     * subject 套餐名称
     * descriptin 详详
     * money 价格http://123.207.119.229:8080
     * out_trade_no 订单号
     * Oid 渠道id
     * ctime 合作商创建的时间
     */
    public void getFEQAlipay(final Activity activity,String subject,String description,double money,final String out_trade_no,String Oid,String ctime){
        this.mActivity = activity;
        mUploadDialog = new UploadDialog(activity,"请求中");
        mUploadDialog.show();
        mMap = new HashMap<>();
        mMap.put("subject",subject);
        mMap.put("total_amount",money);
        mMap.put("body",description);
        mMap.put("out_trade_no",out_trade_no);
        mMap.put("Oid",Oid);
        mMap.put("ctime",ctime);
        mLogger.info("getFEQAlipay()---支付宝>subject:"+subject+"+money:"+money+"+description:"+"+description:"+description+"out_trade_no:"+out_trade_no+"Oid"+Oid+"ctime"+ctime+"...NF_callid...");
        GreenTreeNetworkUtil.getInstance().doPost(activity,Url.mWINATIAIRIP+Url.WFQ_LIPAY,1,mMap,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    mLogger.info("getFEQAlipay()---支付宝>onSuccess()--String--"+response);
                    mUploadDialog.dismiss();
                    JSONObject jsonArray = new JSONObject(response);
                    EventBus.getDefault().post("state");
                    if(jsonArray.getInt("code") == 1){
                        String orderStr = jsonArray.getString("orderStr");
                        SharedPreferencesUtils.setParam(activity,PAY_ORSER,out_trade_no);
                        getAlipay(orderStr);
                    }else if(jsonArray.getInt("code") == 0){
                        String string = jsonArray.getString("orderStr");
                        Toast.makeText(activity,string,Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(activity,"解析后台数据异常",Toast.LENGTH_SHORT).show();
                }
            }

            @Override public void onFailure(Throwable error) {
                EventBus.getDefault().post("state");
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(mActivity, error.toString());
            }
        });
    }

    /**
     * 微信  先调用自己后台
     * name 套餐名称
     * descriptin 详详
     * money 价格
     */
    public void getFEQWeChatPay(final Activity activity, String subject, String description,double money,final String out_trade_no, String Oid, String ctime){
        this.mActivity = activity;
        mUploadDialog = new UploadDialog(activity,"请求中");
        mUploadDialog.show();
        mMap = new HashMap<>();
        mMap.put("subject",subject);  mMap.put("total_amount",(int)(money*100));    mMap.put("body",description);
        mMap.put("out_trade_no",out_trade_no);
        mMap.put("Oid",Oid);          mMap.put("ctime",ctime);
        mMap.put("appName",1);
        mLogger.info("getFEQWeChatPay()---微信>subject:"+subject+"+money:"+(int)(money*100)+"+description:"+description+"out_trade_no:"+out_trade_no+"   Oid"+Oid+"ctime"+ctime);
        GreenTreeNetworkUtil.getInstance().doPost(activity,Url.mWINATIAIRIP+ Url.WFQ_WXPAY,1,mMap,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    mUploadDialog.dismiss();
                    mLogger.info("getFEQWeChatPay()---微信>onSuccess()--String--"+response);
                    EventBus.getDefault().post("state");
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject jsonArray = jsonObject.getJSONObject("parameterMap");
                    String noncestr = jsonArray.getString("noncestr");
                    String packageValue = jsonArray.getString("package");
                    String partnerid = jsonArray.getString("partnerid");
                    String sign = jsonArray.getString("sign");
                    String timestamp = jsonArray.getString("timestamp");
                    String prepayid = jsonArray.getString("prepayid");
                    SharedPreferencesUtils.setParam(activity,PAY_ORSER,out_trade_no);
                    getWeChatPay(activity,prepayid,packageValue,noncestr,timestamp,sign,partnerid);

                } catch (JSONException e) {
                    e.printStackTrace();
                    mLogger.info("getFEQWeChatPay()---微信>onSuccess()--String--9999");
                    Toast.makeText(activity,"解析后台数据异常",Toast.LENGTH_SHORT).show();
                }
            }

            @Override public void onFailure(Throwable error) {
                EventBus.getDefault().post("state");
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(mActivity, error.toString());
            }
        });
    }

    /**
     * 支付结果的查询
     */
    private void getQueryPay(String order){
      Map<String,Object> map = new HashMap<>();
      map.put("order_id",order);
      map.put("Oid","0433536409");
      mLogger.info("getQueryPay()---支付宝结果查询-->order--"+order);
      GreenTreeNetworkUtil.getInstance().doPost(mActivity,Url.mWINATIAIRIP + Url.WFQ_QUERY,1,map,new RequestDataCallback() {
         @Override
         public void onSuccess(String response) {
             try {
                 mLogger.info("getQueryPay()---onSuccess（）-->String--"+response);
                 JSONObject jsonObject = new JSONObject(response);
                 LogUtil.eE("",response);
                 if(jsonObject.getInt("code") == 1){
                     JSONArray jsonArray = jsonObject.getJSONArray("list");
                     if(jsonArray !=null){
                         JSONObject jsonObject1 = (JSONObject) jsonArray.get(0);
                         if(jsonObject1.getInt("status") == 2){
                             String commodity = (String) SharedPreferencesUtils.getParam(mActivity,PAY_COMMODITY,"");
                             // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。 http://123.207.119.229:8080/internet/return_url.jsp
                             if(commodity.equals("会员购买") || commodity.equals("套餐购买")){
                                 SharedPreferencesUtils.setParam(mActivity,HomeUtil.mVIPSTATE,true);
                                 EventBus.getDefault().post("vip");
                             }else if(commodity.equals("余额充值")){
                                 JumpActivityUtils.getInstance().jumpWebView(mActivity,Url.mATIAIRIP + Url.getUrlNew().WALLET,"我的钱包");
                             }
                             if(commodity.equals("套餐购买") || commodity.equals("时长充值") ){
                                 EventBus.getDefault().post("balance");
                             }
                             if(commodity.equals("会员购买") || commodity.equals("时长充值")){
                                 Intent intent = new Intent(HomeActivity.mAction);
                                 intent.putExtra("wifi","updata_coupon");
                                 mActivity.sendBroadcast(intent);
                             }
                             mActivity.finish();
                             getBrokenNetwork(1);
                             Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT).show();
                         }else {
                             getBrokenNetwork(0);
                             Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();
                         }
                     }else {
                         getBrokenNetwork(0);
                         Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();
                     }

                 }else{
                     getBrokenNetwork(0);
                     Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();
                 }

             } catch (JSONException e) {e.printStackTrace();
                 getBrokenNetwork(0);
                 Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();}
         }

         @Override
         public void onFailure(Throwable error) {
          getBrokenNetwork(0);
          Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT).show();
          StringUtil.getStringUtilNew().getExceptionCode(mActivity,error.toString());
         }
     });
    }

    /**
     * 执行断网
     */
    private void getBrokenNetwork(int type){
        if(Url.getUrlNew().getNETWORKING_ATATE() == 1){
            if(type == 1){
                NetWorkstateUtil.getInstance().getBrokenNetwork(mActivity,null,1);
                Url.getUrlNew().setIsonResumeJudge(false);
                HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Url.getUrlNew().setIsonResumeJudge(true);
                    }
                },1500);
            }
        }
    }
}
